package com.zzw.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zzw.bean.SysUser;
import com.zzw.utils.RedisUtil;
import com.zzw.utils.WebUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import com.zzw.bean.Msg;
import com.zzw.bean.Roles;
import com.zzw.service.RolesService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 角色管理控制器
 * @author 赵志伟
 * @version 1.0
 */
@SuppressWarnings({"all"})
@Slf4j
@Controller
@RequestMapping("roles")
@Api(tags = "角色管理接口")
public class RolesController {

    @Autowired
    private RolesService rolesService;

    @ApiOperation(value = "角色管理页面", notes = "跳转到角色管理列表页面")
    @RequiresPermissions("roles:view")
    @RequestMapping("list")
    public String list() {
        return "roles/list";
    }

    @ApiOperation(value = "角色Demo页面", notes = "跳转到角色Demo页面")
    @RequestMapping("demo")
    public String demo() {
        return "roles/demo";
    }

    @ApiOperation(value = "角色列表数据", notes = "分页查询角色列表数据")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "当前页码", required = false, dataType = "Integer", paramType = "query", defaultValue = "1"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer", paramType = "query", defaultValue = "10"),
        @ApiImplicitParam(name = "sort", value = "排序字段", required = false, dataType = "String", paramType = "query"),
        @ApiImplicitParam(name = "order", value = "排序方式", required = false, dataType = "String", paramType = "query")
    })
    @RequestMapping("/selectRolesList")
    @ResponseBody
    public Msg selectRolesList(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                               @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                               @RequestParam(value = "sort", defaultValue = "") String sort,
                               @RequestParam(value = "order", defaultValue = "") String order,
                               Roles role) {
        PageHelper.startPage(pageNum, pageSize, WebUtils.getOrderBy(sort, order));

        List<Roles> roles = rolesService.selectRolesList(role);
        PageInfo pageInfo = new PageInfo(roles, pageSize);

        return Msg.success().add("pageInfo", pageInfo);
    }

    @ApiOperation(value = "查询所有角色", notes = "根据条件查询所有角色列表（不分页）")
    @RequestMapping("/selectRoles")
    @ResponseBody
    public Msg selectRoles(Roles role) {
        List<Roles> roles = rolesService.selectRolesList(role);
        return Msg.success().add("roles", roles);
    }

    @ApiOperation(value = "查询用户角色", notes = "根据用户ID查询该用户拥有的所有角色")
    @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "Integer", paramType = "query")
    @RequestMapping("/selectRolesByUserId")
    @ResponseBody
    public Msg selectRolesByUserId(@RequestParam("userId") Integer userId) {
        List<Roles> roles = rolesService.selectRolesByUserId(userId);
        return Msg.success().add("roles", roles);
    }

    @ApiOperation(value = "删除角色", notes = "根据ID删除角色")
    @ApiImplicitParam(name = "id", value = "角色ID", required = true, dataType = "Integer", paramType = "query")
    @RequiresPermissions("roles:delete")
    @RequestMapping("/delete")
    @ResponseBody
    public Msg delete(Integer id) {
        return Msg.success(rolesService.delete(id));
    }

    @ApiOperation(value = "更新角色", notes = "更新角色信息")
    @RequiresPermissions("roles:update")
    @RequestMapping("/update")
    @ResponseBody
    public Msg update(@RequestBody Roles role) {
        return Msg.success(rolesService.update(role));
    }

    @ApiOperation(value = "添加角色", notes = "添加新角色")
    @RequiresPermissions("roles:add")
    @RequestMapping("/add")
    @ResponseBody
    public Msg add(@RequestBody Roles role) {
        return Msg.success(rolesService.insert(role));
    }

    @ApiOperation(value = "测试权限", notes = "测试用户权限")
    @RequestMapping("/testPermission")
    @ResponseBody
    public Msg testPermission() {
        return Msg.success().setMsg("权限测试成功");
    }

    /**
     * 获取当前用户的权限列表
     * 用于前端权限控制
     */
    @ApiOperation(value = "获取权限列表", notes = "获取当前用户的权限列表，用于前端权限控制")
    @GetMapping("/getUserPermissions")
    @ResponseBody
    public Msg getUserPermissions() {
        try {
            // 获取当前登录的用户
            Subject subject = SecurityUtils.getSubject();
            if (!subject.isAuthenticated()) {
                return Msg.fail().setMsg("用户未登录");
            }

            // 从Subject中获取用户对象
            SysUser user = (SysUser) subject.getPrincipal();
            if (user == null) {
                return Msg.fail().setMsg("获取用户信息失败");
            }

            // 调用Service获取用户权限
            List<String> permissions = rolesService.getUserPermissions(user.getId());

            return Msg.success().add("permissions", permissions);
        } catch (Exception e) {
            e.printStackTrace();
            return Msg.fail().setMsg("获取权限列表失败：" + e.getMessage());
        }
    }
}
